package top.maof.book.controller;

import io.swagger.annotations.ApiOperation;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import top.maof.book.model.Role;
import top.maof.book.model.Web;
import top.maof.book.result.ApiResponse;
import top.maof.book.result.PageData;
import top.maof.book.result.PageWrap;
import top.maof.book.result.Result;
import top.maof.book.service.WebService;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by CodeX4J.
 */
@Controller
@RequestMapping("/web")
@ResponseBody
public class WebController {
    @Autowired
    private WebService webService;

    @RequiresRoles({Role.ADMIN})
    @ApiOperation("新建")
    @PostMapping("/create")
    public ApiResponse create(@RequestBody Web web) {
        return ApiResponse.success(webService.save(web));
    }

    @RequiresRoles({Role.ADMIN})
    @ApiOperation("根据ID删除")
    @GetMapping("/delete/{id}")
    public ApiResponse deleteById(@PathVariable Integer id) {
        webService.removeById(id);
        return ApiResponse.success(null);
    }

    @RequiresRoles({Role.ADMIN})
    @ApiOperation("批量删除")
    @GetMapping("/delete/batch")
    public ApiResponse deleteByIdInBatch(@RequestParam String ids) {
        String[] idArray = ids.split(",");
        List<Integer> idList = new ArrayList<>();
        for (String id : idArray) {
            idList.add(Integer.valueOf(id));
        }
        webService.removeBatchByIds(idList);
        return ApiResponse.success(null);
    }

    @RequiresRoles({Role.ADMIN})
    @ApiOperation("根据ID修改")
    @PostMapping("/updateById")
    public ApiResponse updateById(@RequestBody Web web) {
        webService.updateById(web);
        return ApiResponse.success(null);
    }

    @RequiresRoles({Role.ADMIN})
    @ApiOperation("分页查询")
    @PostMapping("/page")
    public ApiResponse<PageData<Web>> findPage(@RequestBody PageWrap<Web> pageWrap) {
        return ApiResponse.success(webService.findPage(pageWrap));
    }


    @PostMapping("")
    @RequiresRoles({Role.ADMIN})
    public Result add(Web web) {
        if (webService.add(web) > 0) return Result.success();
        return Result.response_400();
    }

    @GetMapping("/{id}")
    public Result find(@PathVariable("id") int id) {
        Web web = webService.find(id);
        if (web != null) return Result.success(web);
        return Result.response_400();
    }

    @PutMapping("")
    @RequiresRoles({Role.ADMIN})
    public Result update(Web web) {
        if (webService.update(web) > 0) Result.success();
        return Result.response_400();
    }

    @DeleteMapping("/{id}")
    @RequiresRoles({Role.ADMIN})
    public Result delete(@PathVariable("id") int id) {
        if (webService.delete(id) > 0) return Result.success();
        return Result.response_400();
    }
}
